// package/pages/addSite/addSite.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    consignee: '',
    latitude: '',
    longitude: '',
    address: '',
    mobile: '',
    houseNumber: '',
    is_default: false,
    address_id: '',
    where: 0,
    multiArray: [],
    multiIndex: [],
    multiArrId: [5827,5828,5975]
  },
  // 加载地址数据
  getData() {
    const that = this;
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getParentRegion).then(res => {
      wx.hideLoading()
      if (res.data.status == 1) {
        that.init(res.data.result.retions)
      }
    })
  },
  init(regions) {
    if (Object.keys(regions).length > 0) {
      const _this = this
      _this.regions = regions
      let multiIndex = [0, 0, 0];
      let multiArrId = _this.data.multiArrId;
      let pid = 0;
      for (let i = 0; i < multiArrId.length; i++) {
        if (i > 0 && pid != multiArrId[i - 1]) {
          break;
        }
        console.log(_this.regions, 8888)
        _this.regions[pid].forEach((value, index) => {
          if (value.id == multiArrId[i]) {

            multiIndex[i] = index;
          }
        })
        pid = multiArrId[i]
      }
      _this.setData({
        multiIndex: multiIndex,
        multiArrId: multiArrId
      })
      _this.setChoose()
    }
  },
  setChoose() {
    const _this = this
    let multiArray = [];
    let multiArrId = [];
    let pid = 0;
    for (let i = 0; i < _this.data.multiIndex.length; i++) {
      console.log(_this.regions[pid], 999)
      _this.regions[pid].forEach((value, index) => {
        if (_this.data.multiIndex[i] == index) {
          multiArray[i] = _this.regions[pid];
          multiArrId.push(value.id);
          pid = value.id
        }
      })

    }
    _this.setData({
      multiArray: multiArray,
      multiArrId: multiArrId
    })
  },
  bindMultiPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value, this.data.multiArrId, 999999)
  },
  bindMultiPickerColumnChange: function (e) {
    // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    let multiIndex = this.data.multiIndex

    for (let i = 0; i < multiIndex.length; i++) {
      if (i == e.detail.column) {
        multiIndex[e.detail.column] = e.detail.value
      }
      if (i > e.detail.column) {
        multiIndex[i] = 0
      }
    }
    this.setData({
      multiIndex: multiIndex
    })
    this.setChoose()
  },
  setName(e) {
    const that = this;
    that.setData({
      consignee: e.detail.value
    })
  },
  setPhone(e) {
    const that = this;
    that.setData({
      mobile: e.detail.value
    })
  },
  setHouseNumber(e) {
    const that = this;
    that.setData({
      houseNumber: e.detail.value
    })
  },

  setIsDefault(e) {
    const that = this;
    that.setData({
      is_default: e.detail.value
    })
  },
  setAddress() {
    const that = this;
    that.checkLocationAuth()
  },
  //获取定位
  getLocation() {
    let that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          address: res.name,
          latitude: res.latitude,
          longitude: res.longitude
        })
      },
      fail: () => {
      }
    })
  },
  //单独提取一个判断用户是否授权定位的函数，在需要的地方直接调用，避免了重复触发getLocation获取定位弹窗	 
  checkLocationAuth() {
    wx.getSetting({
      success: (res) => {
        let authSetting = res.authSetting
        if (authSetting['scope.userLocation']) {
          // 已授权
          this.getLocation()

        } else if (authSetting['scope.userLocation'] === false) {

          wx.showModal({
            title: '您未开启地理位置授权',
            content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting()
              }
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => {
              this.getLocation()
            },
            fail: () => {
              wx.showModal({
                title: '您未开启地理位置授权',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                success: (res) => {
                  if (res.confirm) {
                    wx.openSetting()
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  address() {
    const that = this;
    if (!that.data.consignee) {
      wx.showToast({
        title: '请填写收货人',
        icon: 'error',
        duration: 2000
      })
    } else if (!that.data.mobile) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'error',
        duration: 2000
      })
    } else if (!that.data.address) {
      wx.showToast({
        title: '请选择地址',
        icon: 'error',
        duration: 2000
      })
    } else if (!that.data.houseNumber) {
      wx.showToast({
        title: '请填写门牌号',
        icon: 'error',
        duration: 2000
      })
    } else {
      let data = {
        consignee: that.data.consignee,
        latitude: that.data.latitude,
        longitude: that.data.longitude,
        address: that.data.address + "|" + that.data.houseNumber,
        mobile: that.data.mobile,
        is_default: that.data.is_default ? 1 : 0,
        address_id: that.data.address_id,
        coordinate: 'GCJ02',
        province: that.data.multiArrId[0],
        city: that.data.multiArrId[1],
        district: that.data.multiArrId[2],
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.addAddress, data).then(res => {
        wx.hideLoading()
        if (res.data.status == 1) {
          if (that.data.where == 1) {
            let pages = getCurrentPages(); //获取小程序页面栈
            let beforePage = pages[pages.length - 3]; //获取上个页面的实例对象
            beforePage.setData({
              address_id: res.data.result
            })
            beforePage.getCart2Data()
            wx.navigateBack({
              delta: 2
            })
          } else {
            wx.navigateBack({
              delta: 1
            })
          }
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            success(res) {
              if (res.confirm) {

              }
            }
          })
        }
      }).catch(err => {
        console.log(err, 888)
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    console.log(options,67676)
    that.getData()
    if (options.where) {
      that.setData({
        where: options.where
      })
    }
    if (options.addressId) {
      that.setData({
        address_id: options.addressId
      })
      let data = {
        coordinate: 'GCJ02'
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.getAddressList, data).then(res => {
        wx.hideLoading()
        if (res.data.status == 1) {
          let addressData = {}
          res.data.result.forEach(item => {
            if (item.address_id == options.addressId) {
              addressData = item;
            }
          })
          // 把详细地址和门牌号拆分
          var strSum = addressData.address.indexOf('|');
          var strLength = addressData.address.length;
          // 门牌号数据
          var str = addressData.address.substring(strSum + 1, strLength);
          // 详细地址数据
          var place = addressData.address.substring(0, strSum);
          let multiArrId = []
          multiArrId.push(addressData.province)
          multiArrId.push(addressData.city)
          multiArrId.push(addressData.district)
          that.setData({
            multiArrId,
            consignee: addressData.consignee,
            mobile: addressData.mobile,
            houseNumber: str,
            address: place,
            is_default: addressData.is_default ? true : false,
            'region[0]': addressData.province_name,
            'region[1]': addressData.city_name,
            'region[2]': addressData.district_name,
            'regionId[0]': addressData.province,
            'regionId[1]': addressData.city,
            'regionId[2]': addressData.district,
            latitude: addressData.latitude,
            longitude: addressData.longitude
          })
        }
      }).catch(err => {
        console.log(err, 888)
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})